// 将本地文件上传至七牛云
import qiniu from 'qiniu';
import fs from 'fs';
import localConfig from '../config/index.js';
import { getFileType } from './getFileType.js'

// 七牛云配置
const { accessKey, secretKey, bucket } = localConfig.qiniu;

// 构建七牛云上传对象
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
const qiniuConfig = new qiniu.conf.Config();
const formUploader = new qiniu.form_up.FormUploader(qiniuConfig);


// 将本地文件上传至七牛云
export function uploadToQiniu(localFilePath, key) {
    // 获取文件类型
    const mimeType = getFileType(localFilePath);
    if (!mimeType) {
        return Promise.reject('Unknown file type');
    }

    const putExtra = new qiniu.form_up.PutExtra();
    putExtra.mimeType = mimeType;
    // 生成七牛云上传 Token
    const options = {
        scope: bucket + ':' + key,
    };
    const putPolicy = new qiniu.rs.PutPolicy(options);
    const uploadToken = putPolicy.uploadToken(mac);

    // 读取本地文件内容
    const fileContent = fs.readFileSync(localFilePath);

    // 上传文件
    return new Promise((resolve, reject) => {
        formUploader.put(uploadToken, key, fileContent, putExtra, function (
            respErr,
            respBody,
            respInfo
        ) {
            if (respErr) {
                reject(respErr);
            }
            if (respInfo.statusCode === 200) {
                // 上传成功
                const url = `http://www.myyaya.com.cn/${key}`;
                resolve(url);
            } else {
                // 上传失败
                reject(respBody);
            }
        });
    });
}